#include <JXRGlue.h>
#include <stdio.h>
#include <stdint.h>

size_t jxr_decode(void **buf, size_t *buf_size, void* outbuf, size_t* outdatalen)
{
    size_t output_value;
	
	//U16* outbufarray;
    //U16** outbuf = &outbufarray;
	//PKAllocAligned(outbuf,2*495*203,128);
	size_t outbuf_size;

    ERR                 err;
    PKCodecFactory*     codec_factory = NULL;
    PKImageDecode*      decoder = NULL;
    PKPixelFormatGUID*  target_format;
    PKRect              rect;

    U8 dres_x=96;
    U8 dres_y=96;
    U8* res_x=&dres_x;
    U8* res_y=&dres_y;

    U16 dheight=0;
    U16 dwidth=0;
    U16* height = &dheight;
    U16* width = &dwidth;

    Call(PKCreateCodecFactory(&codec_factory, WMP_SDK_VERSION));

    char *pExt = NULL;
    const PKIID* pIID = NULL;

    struct WMPStream* pStream = NULL;

    // create stream
    Call(CreateWS_Memory(&pStream, *buf, *buf_size));
    // Create decoder
    Call(PKCodecFactory_CreateCodec(&IID_PKImageWmpDecode, (void **) &decoder));
    //decoder->WMP.wmiSCP.bfBitstreamFormat = SPATIAL;
    decoder->WMP.wmiSCP.bVerbose = TRUE;

    // attach stream to decoder
    Call(decoder->Initialize(decoder, pStream)); //segfault
    decoder->fStreamOwner = !0;

    Call(decoder->GetResolution(decoder, res_x, res_y));
    Call(decoder->GetSize(decoder, width, height));
	PKPixelFormatGUID pixel_format;
    Call(decoder->GetPixelFormat(decoder, &pixel_format));

    decoder->guidPixFormat = GUID_PKPixelFormat16bppGray;
    decoder->WMP.wmiI.cfColorFormat = Y_ONLY;

    printf("\t\tformat control %d\n\n",IsEqualGUID(&pixel_format,&GUID_PKPixelFormat16bppGray));

    U32 stride = 2**width;

    outbuf_size = 2*(*width)*(*height);

    rect.X = 0;
    rect.Y = 0;
    rect.Width = *width;
    rect.Height = *height;

    Call(decoder->Copy(decoder, &rect, outbuf, stride));

	//replace buffer and free memory
	*outdatalen = outbuf_size;

    Cleanup:
		printf("failing and cleaning up: nothing to be done");
        if (decoder)
            decoder->Release(&decoder);
        
        if (codec_factory)
            codec_factory->Release(&codec_factory);

    return 1;
}
